layui.define(['jm'], function (exports) {
    var admin = layui.admin
        , $ = layui.$
        , setter = layui.setter
        , layer = layui.layer
        , element = layui.element
        , form = layui.form
        , laytpl = layui.laytpl
        , jm = layui.jm
        , router = layui.router();

    var currentRouter = (function () {
        if (router.href == '/' || !router.href) {
            return '/'
        } else {
            return router.href.replace('/', '')
        }
    })();
    var menustr = ``;
    function bulidMoreMenu(data) {
        menustr += `<dl class="layui-nav-child">`
        data.forEach(item => {
            if (item.children && item.children.length != 0) {
                menustr += `
                <dd>
                    <a href="javascript:;">
                       ${item.icon ? `<i class="layui-icon ${item.icon}"></i>` : ''}
                        <cite>${item.title}</cite> 
                        <i class="layui-icon layui-icon-down layui-nav-more"></i>
                    </a>`
                bulidMoreMenu(item.children)
                menustr += `</dd>`
            } else {
                menustr += `
                <dd class="${item.url == currentRouter ? 'layui-this' : ''}">
                    <a href="javascript:;" lay-href="${item.url ? item.url : 'error/404.html'}">
                      ${item.icon ? `<i class="layui-icon ${item.icon}"></i>` : ''}
                        <cite>${item.title}</cite> 
                    </a>
                </dd> 
                `
            }
        })
        menustr += `</dl>`

    }
    function convertToLayuiMenu(originalData) {
        const groups = {};
        // 1. 按pid分组
        originalData.forEach(item => {
            const pid = item.pid;
            if (!groups[pid]) groups[pid] = [];
            groups[pid].push(item);
        });

        // 2. 递归构建树 + 排序
        const buildTree = (pid) => {
            return (groups[pid] || [])
                .sort((a, b) => a.order_num - b.order_num)
                .map(node => ({
                    title: node.menuname,
                    url: node.menulink,
                    ...(node.icon && { icon: node.icon }), // 仅当icon存在时添加
                    children: buildTree(node.id)
                }));
        };

        // 3. 从pid=1开始构建
        return buildTree(1);
    }
    function bulidMenuStr(data) {
        data.forEach(item => {
            if (item.children && item.children.length != 0) {
                menustr += `
                <li class="layui-nav-item">
                    <a href="javascript:;" lay-tips="${item.title}" lay-direction="2"> 
                    ${item.icon ? `<i class="layui-icon ${item.icon}"></i>` : ''}
                        <cite>${item.title}</cite> 
                        <i class="layui-icon layui-icon-down layui-nav-more"></i>
                    </a>
                `
                bulidMoreMenu(item.children)
                menustr += `</li>`
            } else {
                menustr += `
                <li class="layui-nav-item ${item.url == currentRouter ? 'layui-this' : ''}"> 
                    <a href="javascript:;" lay-href="${item.url ? item.url : 'error/404.html'}" lay-tips="${item.title}"  lay-direction="2"> 
                     ${item.icon ? `<i class="layui-icon ${item.icon}"></i>` : ''}
                        <cite>${item.title}</cite>
                    </a>
                </li>`
            }
        });
    }

    // 菜单数据
    var loadIndex = layer.load(0, {
        time: 0,
        shade: 0.15
    })

    var cursys = JSON.parse(layui.sessionData(setter.tableName + 'platform').platform)
    // system 信息
    admin.req({
        url: 'sysuser/getusermenubyid/' + Number(cursys.key),
        type: 'get',
        done: function (res) {
            if (res.successful) {
                var curmenudata = convertToLayuiMenu(res.data);
                bulidMenuStr(curmenudata);
                $('#LAY-system-side-menu').html(menustr)
                element.render('nav', 'layadmin-system-side-menu');
                $('#LAY-system-side-menu').find(`[lay-href="${currentRouter}"]`).parents('dd,li').addClass('layui-nav-itemed');
                layer.close(loadIndex)
            } else {
                layer.close(loadIndex)
                if (typeof res?.msg === 'string') {
                    layer.msg(res.msg);
                }
                else {
                    layer.msg(res?.msg?.[""]?.[0] || "Unknown error");
                }
            }
        }
    });
    // 用户信息数据
    admin.req({
        url: 'sysUser/getUserInfo',
        type: 'get',
        done: function (res) {
            if (res.successful) {
                var userTpl = document.getElementById('userifo').innerHTML;
                laytpl(userTpl).render(res.data, function (str) {

                    $('#userifo').parent().html(str)
                });
                layer.close(loadIndex)
            }
        }
    });
    // 系统信息数据
    var framUrl = JSON.parse(layui.sessionData(setter.tableName + 'platform')['platform']).url;
    $('.layadmin-iframe').attr('src', framUrl);

    // 消息数据获取
    var ifoData = {
        "code": 0
        , "msg": ""
        , "data": {
            "newmsg": 3
        }
    }
    var ScreenState = layui.sessionData(setter.tableName)['ScreenState'];
    if (ScreenState === 1) {
        lockscreene();
    }

    admin.events.logout = function () {
        admin.exit();
    };
    /*锁屏方法*/
    function lockscreene() {
        layer.open({
            type: 1,
            title: false, // 禁用标题栏
            closeBtn: false, // 禁用默认关闭按钮
            area: ['100%', '100%'],
            scrollbar: false, // 暂时屏蔽浏览器滚动条
            anim: -1, // 禁用弹出动画
            isOutAnim: false, // 禁用关闭动画
            resize: false,  // 禁用右下角拉伸尺寸
            id: 'ID-layer-demo-inst',
            skin: 'class-demo-layer-lockscreen', // className
            content: ['<div class="layui-form">',
                '<div class="layui-input-wrap">',
                '<input type="password" class="class-demo-layer-pin" lay-affix="eye">',
                '<div class="layui-input-suffix">',
                '<i class="layui-icon layui-icon-right" id="ID-layer-demo-unlock"></i>',
                '</div>',
                '</div>',
                '<div>输入登录密码后回车，即可退出锁屏</div>',
                '</div>'].join(''),
            success: function (layero, index) {
                var input = layero.find('input');
                var PASS = layui.sessionData(setter.tableName)['UserScreenValue'];
                layui.sessionData(setter.tableName, {
                    key: 'ScreenState',
                    value: 1
                });
                form.render(); // 表单组件渲染
                input.focus();
                // 点击解锁按钮
                var elemUnlock = layero.find('#ID-layer-demo-unlock');
                elemUnlock.on('click', function () {
                    var screenvalue = jm.s4.encryptData_ECB($.trim(input[0].value));
                    if (screenvalue === PASS) {
                        layui.sessionData(setter.tableName, {
                            key: 'ScreenState',
                            value: 0
                        });
                        layer.close(index);
                        layer.closeLast('dialog'); // 关闭最新打开的信息框
                    } else {
                        layer.msg('锁屏密码输入有误', { offset: '16px', anim: 'slideDown' })
                        input.focus();
                    }
                });
                // 回车
                input.on('keyup', function (e) {
                    var elem = this;
                    var keyCode = e.keyCode;
                    if (keyCode === 13) {
                        elemUnlock.trigger('click');
                    }
                });
            }
        })
    }

    /*开启锁屏*/
    admin.events.lockscreen = function () {
        lockscreene();
    };
    admin.events.goback = function () {
        layui.sessionData(setter.tableName + 'platform', {
            key: 'platform',
            remove: true
        });
        location.href = "/index.html";
    };
    exports('layout', {})
});